import { Application } from "egg";
import * as AutoIncrementFactory from "mongoose-sequence";
import { ObjectId } from "mongoose";
export interface UserProps {
  phoneNumber: string; // 电话号码<可登陆>
  nikeName: string; // 姓名
  password: string; // 密码
  picture?: string; // 头像
  role: []; // 角色ID
  company: ObjectId; // 公司ID
  department?: ObjectId; // 部门ID
  position?: ObjectId; // 职务ID
  is_delete: boolean; // 是否删除
}
function initUserModel(app: Application) {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  const AutoIncrement = AutoIncrementFactory(mongoose);
  const UserScheme = new Schema<UserProps>(
    {
      password: { type: String },
      nikeName: { type: String, required: true },
      picture: { type: String, default: "" },
      phoneNumber: { type: String, unique: true, required: true },
      role: { type: Array },
      company: { type: Schema.Types.ObjectId, ref: "Company" },
      department: {
        type: Schema.Types.ObjectId,
        ref: "Department",
        default: "",
      },
      position: { type: Schema.Types.ObjectId, ref: "Position", default: "" },
      is_delete: { type: Boolean, default: false },
    },
    {
      timestamps: true,
      toJSON: {
        transform(_doc, ret) {
          delete ret.password;
          delete ret.__v;
        },
      },
    }
  );
  UserScheme.plugin(AutoIncrement, {
    inc_field: "id",
    id: "User_counter",
  });
  return app.mongoose.model<UserProps>("User", UserScheme);
}

export default initUserModel;
